package device

import (
	"backend/internal/common/errorx"
	"backend/internal/db/model"
	"backend/internal/svc"
	"backend/internal/types"
	"context"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetDeviceListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetDeviceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDeviceListLogic {
	return &GetDeviceListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDeviceListLogic) GetDeviceList() (resp *types.DeviceListResp, err error) {
	// 初始化响应结构
	resp = &types.DeviceListResp{
		Status: http.StatusOK,
		Data:   make([]types.DeviceInfo, 0),
	}

	// 查询所有设备记录
	var devices []model.Device
	if err := l.svcCtx.GormDB.Find(&devices).Error; err != nil {
		errorStr := fmt.Sprintf("查询设备列表失败: %v", err)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(500, errorStr)
	}
	l.svcCtx.ClientManager.SetAllClient(devices)

	// 转换模型到响应结构
	for _, d := range devices {
		client := l.svcCtx.ClientManager.GetClient(d.Name)
		connected := false
		if client != nil {
			connected = client.Connected
		}
		resp.Data = append(resp.Data, types.DeviceInfo{
			ID:          int64(d.ID),
			Name:        d.Name,
			IP:          d.IP,
			Port:        d.Port,
			Protocol:    d.Protocol,
			IsConnected: connected,
		})
	}
	logx.Infof("查询设备列表成功: %v", resp.Data)
	resp.Msg = "查询设备列表成功"
	return resp, nil
}
